package com.hwpt.hwaccount.feature.personalinfo;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.hwpt.hwaccount.R;
import com.hwpt.hwaccount.core.data.local.entity.UserEntity;
import com.hwpt.hwaccount.core.utils.AvatarImageUtils;

import java.util.Calendar;

public class PersonalInfoActivity extends AppCompatActivity implements PersonalInfoContract.View {

    private PersonalInfoContract.Presenter presenter;

    private ImageView avatarImage;
    private TextView nicknameText;
    private TextView userIdText;
    private TextView genderText;
    private TextView birthdayText;
    private TextView regionText;
    private TextView realnameText;
    private View nicknameLayout;
    private View genderLayout;
    private View birthdayLayout;
    private View regionLayout;
    private View realnameLayout;
    private View idCard;

    private static final int PICK_IMAGE_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personalinfo);

        initView();

        PersonalInfoContract.Model model = new PersonalInfoModel(this);
        presenter = new PersonalInfoPresenter(model);
        presenter.attachView(this);

        presenter.loadUserInfo();
    }

    private void initView() {
        avatarImage = findViewById(R.id.avatar_image);
        nicknameText = findViewById(R.id.nickname_text);
        userIdText = findViewById(R.id.user_id_text);
        genderText = findViewById(R.id.gender_text);
        birthdayText = findViewById(R.id.birthday_text);
        regionText = findViewById(R.id.region_text);
        realnameText = findViewById(R.id.realname_text);

        nicknameLayout = findViewById(R.id.nickname_layout);
        genderLayout = findViewById(R.id.gender_layout);
        birthdayLayout = findViewById(R.id.birthday_layout);
        regionLayout = findViewById(R.id.region_layout);
        realnameLayout = findViewById(R.id.realname_layout);


        nicknameLayout.setOnClickListener(v -> showNicknameDialog());
        genderLayout.setOnClickListener(v -> showGenderDialog());
        birthdayLayout.setOnClickListener(v -> showBirthdayDialog());
        regionLayout.setOnClickListener(v -> showRegionDialog());
        realnameLayout.setOnClickListener(v -> showRealnameDialog());
        avatarImage.setOnClickListener(v -> showAvatarDialog());
    }

    @Override
    public void showUserInfo(UserEntity user) {
        nicknameText.setText(user.getNickname() != null ? user.getNickname() : "未设置");
        userIdText.setText(user.getHanWangId());

        String genderStr = "0";

        Integer sex = user.getGender();
        if (sex == null) {
            genderText.setText("未设置");
            return;
        }
        switch (user.getGender()) {
            case 1:
                genderStr = "男";
                break;
            case 2:
                genderStr = "女";
                break;
        }
        genderText.setText(genderStr);

        birthdayText.setText(user.getBirthday() != null ? user.getBirthday() : "未设置");
        regionText.setText(user.getCountryRegion() != null ? user.getCountryRegion() : "未设置");

        String realnameStatus = (user.getRealName() != null && user.getIdCard() != null)
                ? "已认证" : "未认证";
        realnameText.setText(realnameStatus);

        AvatarImageUtils.loadAvatarImage(this, user, avatarImage);
    }

    @Override
    public void showAvatar(Uri imageUri) {
        try {
            Glide.with(this)
                    .load(imageUri)
                    .circleCrop()
                    .placeholder(R.drawable.ic_profile)
                    .error(R.drawable.ic_profile)
                    .into(avatarImage);
        } catch (Exception e) {
            showAvatarLoadError("图片加载失败");
        }
    }

    @Override
    public void showAvatarLoadError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showSuccess(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }


    private void showNicknameDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改昵称");

        View view = getLayoutInflater().inflate(R.layout.dialog_edit_text, null);
        EditText editText = view.findViewById(R.id.edit_text);
        editText.setHint("请输入昵称");
        editText.setText(nicknameText.getText().toString());

        builder.setView(view);
        builder.setPositiveButton("确定", (dialog, which) -> {
            String newNickname = editText.getText().toString().trim();
            if (!newNickname.isEmpty()) {
                presenter.updateNickname(newNickname);
            } else {
                showError("昵称不能为空");
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showGenderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择性别");

        String[] genders = {"男", "女"};
        builder.setItems(genders, (dialog, which) -> {
            int genderValue = which + 1;
            presenter.updateGender(genderValue);
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showBirthdayDialog() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    String birthday = selectedYear + "-" + (selectedMonth + 1) + "-" + selectedDay;
                    presenter.updateBirthday(birthday);
                },
                year, month, day
        );

        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        datePickerDialog.setTitle("选择生日");
        datePickerDialog.show();
    }

    private void showRegionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择地区");

        View view = getLayoutInflater().inflate(R.layout.dialog_region, null);
        Spinner countrySpinner = view.findViewById(R.id.country_spinner);
        Spinner provinceSpinner = view.findViewById(R.id.province_spinner);
        Spinner citySpinner = view.findViewById(R.id.city_spinner);

        ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(
                this, R.array.countries_array, android.R.layout.simple_spinner_item);
        countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        countrySpinner.setAdapter(countryAdapter);

        ArrayAdapter<CharSequence> provinceAdapter = ArrayAdapter.createFromResource(
                this, R.array.provinces_array, android.R.layout.simple_spinner_item);
        provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        provinceSpinner.setAdapter(provinceAdapter);

        ArrayAdapter<CharSequence> cityAdapter = ArrayAdapter.createFromResource(
                this, R.array.cities_array, android.R.layout.simple_spinner_item);
        cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        citySpinner.setAdapter(cityAdapter);

        builder.setView(view);
        builder.setPositiveButton("确定", (dialog, which) -> {
            String country = countrySpinner.getSelectedItem().toString();
            String province = provinceSpinner.getSelectedItem().toString();
            String city = citySpinner.getSelectedItem().toString();
            String region = country + " " + province + " " + city;
            presenter.updateRegion(region);
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }


    private void showRealnameDialog() {
        // 先查询数据库中的用户信息
        presenter.checkRealnameInfo();
    }

    @Override
    public void showRealnameInputDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("实名认证");

        View view = getLayoutInflater().inflate(R.layout.dialog_realname, null);
        EditText realnameEditText = view.findViewById(R.id.realname_edit_text);
        EditText idCardEditText = view.findViewById(R.id.id_card_edit_text);

        builder.setView(view);
        builder.setPositiveButton("提交认证", (dialog, which) -> {
            String realName = realnameEditText.getText().toString().trim();
            String idCard = idCardEditText.getText().toString().trim();

            if (realName.isEmpty() || idCard.isEmpty()) {
                showError("请填写完整信息");
                return;
            }

            presenter.doRealNameAuth(realName, idCard);
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    @Override
    public void showRealnameInfo(String maskedRealName, String maskedIdCard) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("实名认证信息");

        String message = "真实姓名: " + maskedRealName + "\n"
                + "身份证号: " + maskedIdCard + "\n\n"
                + "已完成实名认证";

        builder.setMessage(message);
        builder.setPositiveButton("确定", null);
        builder.show();
    }


/*    public void showRealnameDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("实名认证");

        View view = getLayoutInflater().inflate(R.layout.dialog_realname, null);
        EditText realnameEditText = view.findViewById(R.id.realname_edit_text);
        EditText idCardEditText = view.findViewById(R.id.id_card_edit_text);

        builder.setView(view);
        builder.setPositiveButton("提交认证", (dialog, which) -> {
            String realName = realnameEditText.getText().toString().trim();
            String idCard = idCardEditText.getText().toString().trim();

            if (realName.isEmpty() || idCard.isEmpty()) {
                showError("请填写完整信息");
                return;
            }

            presenter.doRealNameAuth(realName, idCard);
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }*/

    private void showAvatarDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择头像");

        String[] options = {"从相册选择", /*"拍照", */"取消"};
        builder.setItems(options, (dialog, which) -> {
            switch (which) {
                case 0:
                    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    galleryIntent.setType("image/*");
                    startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
                    break;
                case 1:
                    showError("拍照功能暂未实现");
                    break;
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PICK_IMAGE_REQUEST && data != null) {
            Uri selectedImage = data.getData();
            if (selectedImage != null) {
                presenter.updateAvatar(selectedImage.toString());
                showAvatar(selectedImage);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter.onDestroy();
        }
        super.onDestroy();
    }
}